package com.mingyizhudao.app.view.notify;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import com.google.gson.Gson;
import com.igexin.sdk.PushConsts;
import com.mingyizhudao.app.utils.CommonUtils;
import com.mingyizhudao.app.utils.Constants;
import com.mingyizhudao.app.view.MainActivity;
import com.mingyizhudao.app.view.WebViewActivity;
import com.mingyizhudao.app.view.login.LoginActivity2;
import com.mingyizhudao.app.view.notify.NotifyBean.ADNotify;
import com.mingyizhudao.app.view.notify.NotifyBean.Notify;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class GeTuiPushReceiver extends BroadcastReceiver {
	private final static String ACTION = "com.updateapk.service";
	@Override
	public void onReceive(final Context context, Intent intent) {

		Bundle bundle = intent.getExtras();

		switch (bundle.getInt(PushConsts.CMD_ACTION)) {
		case PushConsts.GET_CLIENTID:

			String cid = bundle.getString("clientid");
			// TODO:处理cid返回
			break;
		case PushConsts.GET_MSG_DATA:

			String taskid = bundle.getString("taskid");
			String messageid = bundle.getString("messageid");
			byte[] payload = bundle.getByteArray("payload");
			if (payload != null) {
				String data = new String(payload);
				System.out.println("透传："+data);
				// TODO:接收处理透传（payload）数据

				try
				{


					Notify notify;
					Gson gson = new Gson();
					if (data!=null&&data.contains("\"{")) {
						String notifyStr = new JSONObject(data).getString("data");
						notify =  gson.fromJson(notifyStr, Notify.class);
					}else {
						NotifyBean notifyBean = gson.fromJson(data, NotifyBean.class);
						notify = notifyBean.getData();
					}
					//Notify notify =  gson.fromJson(notifyBean.getData(), Notify.class);
					Bundle bundle2 = new Bundle();

					String code[] = notify.getAdVersionCode();
					if (isCan(code,context)) {

						if( "appfix".equals( notify.getType() ) ){

							Intent intentService = new Intent();
							intentService.putExtra("download_url", notify.getUrl());
							intentService.setAction(ACTION);
							intentService.setPackage(context.getPackageName());
							intentService.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
							context.startService(intentService);
							
						}
						else if( "web".equals( notify.getType() ) )
						{

							if (!isRunningForeground(context)) {

								Intent main = new Intent(context, MainActivity.class);
								main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
								context.startActivity(main);
							}
							bundle2.putString(Constants.PARM_ACTION_URL, notify.getUrl());
							bundle2.putString(Constants.PARM_PAGE_TITLE, notify.getTitle());

							//打开自定义的Activity
							final Intent i = new Intent(context, WebViewActivity.class);
							i.putExtras(bundle2);
							//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );

							context.startActivity(i);
							//    						}
						}else if ("app".equals( notify.getType() )) {

							//    					String code[] = notify.getAdVersionCode();
							//
							//    					if (isCan(code,context)) {

							if (!isRunningForeground(context)) {

								Intent main = new Intent(context, MainActivity.class);
								main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
								context.startActivity(main);
							}
							
							if ("1".equals(notify.getIsNeedLogin())) {

								String mobile =CommonUtils.getMobile( context );
								String token =CommonUtils.getToken( context );


								if( token!=null&&token.length()>0&&mobile!=null&&mobile.length()>0 )//已经登录
								{
									ADNotify adNotify = notify.getAd();
									Class<?> cName = Class.forName(adNotify.getClassname());
									Map<String,Object> param =  adNotify.getParam();
									for (Map.Entry<String, Object> entry : param.entrySet()) {
										String key = entry.getKey();
										String value = entry.getValue().toString();
										bundle2.putString(key, value);
									} 
									//打开自定义的Activity
									Intent i = new Intent(context, cName);
									i.putExtras(bundle2);
									//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
									context.startActivity(i);
								}else {//没有登录，跳转登录

									ADNotify adNotify = notify.getAd();
									bundle2.putSerializable("adNotify", adNotify);
									//打开自定义的Activity
									Intent i = new Intent(context, LoginActivity2.class);
									i.putExtras(bundle2);
									//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
									context.startActivity(i);

								}


							}else {

								ADNotify adNotify = notify.getAd();
								Class<?> cName = Class.forName(adNotify.getClassname());
								Map<String,Object> param =  adNotify.getParam();
								for (Map.Entry<String, Object> entry : param.entrySet()) {
									String key = entry.getKey();
									String value = entry.getValue().toString();
									bundle2.putString(key, value);
								}



								//打开自定义的Activity
								Intent i = new Intent(context, cName);
								i.putExtras(bundle2);
								//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
								i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
								context.startActivity(i);
							}


						}
						
					}else {
							if (!isRunningForeground(context)) {
	
								Intent main = new Intent(context, MainActivity.class);
								main.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
								context.startActivity(main);
							}
								Toast.makeText(context, "请更新版本后再查看详情", Toast.LENGTH_SHORT).show();
						}


				}
				catch( Exception e )
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 

			}
			break;
		default:
			break;
		}
	}


	private boolean isCan(String api[],Context context){

		String code = ""+CommonUtils.getAppVersionCode(context);

		if (api==null) {
			return false;
		}else {
			for (int i = 0; i < api.length; i++) {
				if (code.equals(api[i]) ) {
					return true;
				}
			}
		}
		return false;

	}


	public boolean isRunningForeground(Context context){  
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);  
		ComponentName cn = am.getRunningTasks(1).get(0).topActivity;  
		String currentPackageName = cn.getPackageName();  
		if(currentPackageName != null && currentPackageName.equals(context.getPackageName())){  
			return true;  
		}  
		return false;  
	} 
}